import axios from "axios";
import { Action, ElMessage, ElMessageBox } from "element-plus";
import { useUserStore } from "@/store/modules/user";
import { REMOVE_TOKEN } from "@/utils/token.ts";
import { useRoute, useRouter } from "vue-router";
import errorCode from "@/utils/request/errorCode";
import { error } from "echarts/types/src/util/log";
import { tansParams } from "@/utils/yixia";
import cache from "@/plugins/cache";


// 是否显示重新登录
export let isRelogin = { show: false };


//创建axios实例
const request = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API /*请求路径*/,
  timeout: 1000000 /*超时时间*/
});
//请求拦截器
/*config配置对象*/
request.interceptors.request.use((config) => {

  // 是否需要设置 token
  const isToken = (config.headers || {}).isToken === false;
  // 是否需要防止数据重复提交
  const isRepeatSubmit = (config.headers || {}).repeatSubmit === false;


  /*config有headers请求头，给服务器携带公共参数*/
  /*给请求添加token*/
  const UserStore = useUserStore();
  if (UserStore.token) {
    config.headers.Authorization = UserStore.token;
  }

  // get请求映射params参数
  if (config.method === "get" && config.params) {
    let url = config.url + "?" + tansParams(config.params);
    url = url.slice(0, -1);
    config.params = {};
    config.url = url;
  }
  if (!isRepeatSubmit && (config.method === "post" || config.method === "put")) {
    const requestObj = {
      url: config.url,
      data: typeof config.data === "object" ? JSON.stringify(config.data) : config.data,
      time: new Date().getTime()
    };
    const sessionObj = cache.session.getJSON("sessionObj");
    if (sessionObj === undefined || sessionObj === null || sessionObj === "") {
      cache.session.setJSON("sessionObj", requestObj);
    } else {
      const s_url = sessionObj.url;                  // 请求地址
      const s_data = sessionObj.data;                // 请求数据
      const s_time = sessionObj.time;                // 请求时间
      const interval = 1000;                         // 间隔时间(ms)，小于此时间视为重复提交
      if (s_data === requestObj.data && requestObj.time - s_time < interval && s_url === requestObj.url) {
        const message = "数据正在处理，请勿重复提交";
        console.warn(`[${s_url}]: ` + message);
        return Promise.reject(new Error(message));
      } else {
        cache.session.setJSON("sessionObj", requestObj);
      }
    }
  }

  return config;
}, error => {
  console.log(error);
  Promise.reject(error);
});

//响应拦截器
request.interceptors.response.use(
  (response) => {
    /*成功回调“*/
    console.log("响应拦截器");
    console.log(response);
    // 未设置状态码则默认成功状态
    const code = response.data.code || 200;
    // 获取错误信息
    const msg = errorCode[code] || response.data.message || errorCode["default"];

    console.log(code);
    console.log(msg);


    // 二进制数据则直接返回
    if (response.request.responseType === "blob" || response.request.responseType === "arraybuffer") {
      return response.data;
    }

    const UserStore = useUserStore();
    /* let $router = useRouter() /!*获取路由器*!/
     let $route = useRoute() /!*获取路由对象*!/*/
    if (code === 401) {

      if (!isRelogin.show) {
        isRelogin.show = true;
        ElMessageBox.confirm("登录状态已过期，您可以继续留在该页面，或者重新登录", "系统提示", {
          confirmButtonText: "重新登录",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          isRelogin.show = false;
          // 退出登录并条状好主页
          UserStore.logout().then(() => {
            location.href = "/index";
          });
        }).catch(() => {
          isRelogin.show = false;
        });
      }
      return Promise.reject("无效的会话，或者会话已过期，请重新登录。");
    } else if (code === 500) {
      ElMessage({ message: msg, type: "error" });
      return Promise.reject(new Error(msg));
    } else if (code === 601) {
      ElMessage({ message: msg, type: "warning" });
      return Promise.reject("error");
    } else if (code !== 200) {
      Notification({ title: msg, type: "error" });
      return Promise.reject("error");
    } else {
      return response.data;
    }
  },
  error => {
    console.log("-----------------------------------");
    console.log("err" + error);
    let { message } = error;
    if (message == "Network Error") {
      message = "后端接口连接异常";
    } else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
      message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    ElMessage({ message: message, type: "error", duration: 5 * 1000 });
    return Promise.reject(error);
  }
);


/*
      /!*token存在*!/
      if (UserStore.token) {
        //REMOVE_TOKEN() //移除token
        /!*ElMessageBox.alert('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
                    confirmButtonText: '重新登录',
                    cancelButtonText: '取消',
                    type: 'warning',
                    callback: (action: Action) => {
                        userStore.hasUserInfo = false;
                        userStore.hasRouter = false;
                        /!*判断query是否有*!/
                        let redirect = $route.query.redirect
                        /!*有redirect就跳到该目录，没有跳到首页*!/
                        $router.push({path:redirect || '/'})
                        ElMessage({
                            type: 'info',
                            message: `action: ${action}`,
                        })
                    },
                })*!/

        ElMessageBox.confirm(
          '登录状态已过期，您可以继续留在该页面，或者重新登录',
          '系统提示',
          {
            distinguishCancelAndClose: true,
            confirmButtonText: '重新登录',
            cancelButtonText: '取消',
          },
        )
          .then(() => {
            ElMessage({
              type: 'success',
              message: 'Changes saved. Proceeding to a new route.',
            })
            UserStore.token = null

            UserStore.hasUserInfo = false
            UserStore.hasMenuRouter = false
            /!*判断query是否有*!/
            let redirect = $route.query.redirect
            /!*有redirect就跳到该目录，没有跳到首页*!/
            $router.push({ path: '/login', query: { redirect: redirect } })
          })
          .catch((action: Action) => {
            ElMessage({
              type: 'info',
              message:
                action === 'cancel'
                  ? 'Changes discarded. Proceeding to a new route.'
                  : 'Stay in the current route',
            })
            UserStore.hasUserInfo = false
            UserStore.hasMenuRouter = false
            /!*判断query是否有*!/
            let redirect = $route.query.redirect
            /!*有redirect就跳到该目录，没有跳到首页*!/
            $router.push({ path: redirect || '/login' })
          })
      }
      return Promise.reject('无效的会话，或者会话已过期，请重新登录。')
    }

    /!*简化数据*!/
    return response.data
  },
  (error) => {
    //处理网络错误
    let msg = ''
    const status = error.response.status
    switch (status) {
      case 401:
        break
      case 403:
        msg = '无权访问'
        break
      case 404:
        msg = '请求地址错误'
        break
      case 500:
        msg = '服务器出现问题'
        break
      default:
        msg = '无网络'
    }
    ElMessage({
      type: 'error',
      message: msg,
    })
    return Promise.reject(error)
  },
)
*/

/*
 *  post请求
 *  url:请求地址
 *  params:参数
 * */
export function post(url: string, params = {}) {
  return new Promise((resolve, reject) => {
    request({
      url: url,
      method: "post",
      data: params
    })
      .then((response) => {
        console.log(response);
        resolve(response);
      })
      .catch((error) => {
        console.log(error);
        reject(error);
      });
  });
}

/*
 *  get请求
 *  url:请求地址
 *  params:参数
 * */
export function get(url: string, params = {}) {
  return new Promise((resolve, reject) => {
    request({
      url: url,
      method: "get",
      data: params
    })
      .then((response) => {
        console.log(response);
        resolve(response);
      })
      .catch((error) => {
        console.log(error);
        reject(error);
      });
  });
}

/*token过期操作*/
function removeToken() {
  const usrStore = useUserStore();
  usrStore.token = "";
  REMOVE_TOKEN();
  /*重定向到login*/
  router.push({ path: "/login" });
  ElMessage("token过期，请重新登陆");
}

/*对外暴露接口*/
export default request;


